<?php

namespace App\Repository;

use App\Models\V1\MemberModel;
use Illuminate\Support\Facades\DB;
use JPush\Client;

trait Comment
{
    /**
     * 修改用户的评论的数据格式
     * @param $data 要改变的数组
     * @param $id 数据的主键的ID
     * @return array
     */
    public function commentForm(array $data, $id)
    {
        $tmps = [];
        foreach ($data as $kk => &$vv) {
            if ($id == $vv['pid']) {
                if ($vv['DeleteMark'] == 1) {//如果没有删除
                    array_push($tmps, $vv);
                }
                $tmp = $vv;
                unset($vv);
                $commentForm = $this->commentForm($data, $tmp['RepID']);
                $tmps        = array_merge($tmps, $commentForm);
            }
        }

        return $tmps;
    }

    //获取所有的评论
    public function getAllComments($commentId, $readPartyId)
    {
        $data     = [];
        $comments = DB::table('commentreply as a')
            ->leftJoin('memberinfo as b', 'b.MemNumber', '=', 'a.MemNumber')
            ->select('a.*', 'b.UserID', 'b.YourName as userName', 'mm.YourName as replyName', 'mm.UserID as replyUserId', 'b.FilePath1 as userAvg')
            ->leftJoin('memberinfo as mm', 'mm.MemNumber', '=', 'a.reply_MemNumber')
            ->where('a.ReaParID', $readPartyId)//读书会的ID
            ->where('a.CommID', $commentId)//读书改进计划的ID
            ->orderBy('RepID')
            ->get();
        foreach ($comments as $key => $com) {
            $com->CommContents = emoji_text_decode($com->CommContents);
            $com->userAvg      = change_member_head_img($com->userAvg);
            if ($com->DeleteMark == 0) {
                unset($comments[$key]);
            } else {
                $data[] = $comments[$key];
            }
        }

        return $data;
    }

    /**
     * 判断当前的用户的角色是否是admin
     * @param $readPartyId 读书的ID
     * @param $userMemberNumber
     * @return int 1为是admin 0为不是admin
     * @internal param 手机号 $mobile
     * @internal param 设备的key值 $key
     */
    public function hasAdmin($readPartyId, $userMemberNumber)
    {
        $readPart     = DB::table('read_party')->where('ReaParID', $readPartyId)->first();
        $memberNumber = $readPart ? $readPart->MemNumber : null;
        $isAdmin      = ($memberNumber == $userMemberNumber) ? 1 : 0;//判断是否是管理员

        return $isAdmin;
    }

    /**
     * 判断用户是否是学习官
     * @param $mobile 当前用户的手机号
     * @param $key 当前设备的key
     * @param $companyId 公司的ID
     * @return int 返回值 1为学习官 0不是学习官
     */
    public function hasDrp($mobile, $key, $companyId)
    {
        $memberInfo = new MemberModel();
        $userInfo   = $memberInfo->get_member_info_by_mobile_key($mobile, $key);
        $userId     = $userInfo->UserID;
//        $isDrop     = DB::table('read_party_member')->where('user_id', $userId)->first(['study_officer']);
        $isDrop = DB::table('company')->where(['drp_user_id' => $userId, 'company_id' => $companyId])->first(['drp_user_id']);
        $isDrop = $isDrop ? 1 : 0;//判断用户是否存在如果存在则为学习官 不存在则不是学习官

        return $isDrop;
    }

    /**
     * 用户是否拥有该条评论
     * @param $memNumber 用户的唯一的编号
     * @return int 如果为1则是当前用户的 为0则不是当前用户吗
     */
    public function hasComment($memNumber)
    {
        $data      = DB::table('commentreply')->where('MemNumber', $memNumber)->first();
        $isComment = $data ? 1 : 0;

        return $isComment;
    }

    /**
     * 判断用户是否是该部门的部门的主管
     * @param $departmentId 部门的ID
     * @return mixed 返回该部门的主管的UserId
     */
    public function hasDepartmentAdmin($departmentId)
    {
        $isAdminUser = DB::table('company_department')->where('department_id', $departmentId)
            ->first(['department_manager']);
        $isAdminUser = $isAdminUser ? $isAdminUser->department_manager : 0;

        return $isAdminUser;
    }

    /**
     * 通过userId用户的id判断用户是否已经删除
     * @param $userId 用户的userId
     * @param $companyId
     * @return int 1是学习官 0不是学习官
     */
    public function isDrp($userId, $companyId)
    {
        $isDrop = DB::table('company')->where(['drp_user_id' => $userId, 'company_id' => $companyId])->first(['drp_user_id']);
//        $isDrop = DB::table('read_party_member')->where('user_id', $userId)->first(['study_officer']);
        $isDrop = $isDrop ? 1 : 0;//判断用户是否存在如果存在则为学习官 不存在则不是学习官

        return $isDrop;
    }

    /**
     * 根据用户的memNumber获取用户的UserID
     * @param $memNumber 用户的唯一的标号
     * @return mixed 返回用户的UserID
     */
    public function getUserIdByMemNumber($memNumber)
    {
        $userId = DB::table('memberinfo')->where('MemNumber', $memNumber)->first(['UserID']);
        $userId = $userId->UserID;

        return $userId;
    }

    /**
     * 根据用户userId换取用户的memNumber
     * @param $userId
     * @return mixed 返回用户的memNumber
     * @internal param 用户的UserId $UserId
     */
    public function getMemNumberByUserId($userId)
    {
        $memNumber = DB::table('memberinfo')->where('UserID', $userId)->first(['MemNumber']);
        $memNumber = $memNumber ? $memNumber->MemNumber : null;

        return $memNumber;
    }

    /**
     * 通过user_id获取用户的城市
     * @param $userId
     * @return mixed
     */
    public function get_city_by_user_id($userId)
    {
        $city = DB::table('memberinfo as m')->select('r.region_name as city', 'rr.region_name as province', 'rrr.region_name as country')
            ->join('region as r', 'm.city', '=', 'r.region_id')
            ->leftJoin('region as rr', 'rr.region_id', '=', 'r.parent_id')
            ->leftJoin('region as rrr', 'rrr.region_id', '=', 'rr.parent_id')
            ->where('m.UserID', $userId)
            ->first();

        return $city;
    }

    //极光推送
    public function JpushContent($msg, $alias, $title, $extras = null)
    {
        $JpushAppk   = config('app.pushAppkey');
        $JpushSecret = config('app.pushSecret');
        $client      = new Client($JpushAppk, $JpushSecret);
        $push        = $client->push();
        if ($alias) {
            $result = $push->setPlatform('all')
                ->addAlias($alias)
                ->options(['apns_production' => true])
                ->iosNotification($msg, [
                    'title'  => $title,
                    'sound'  => 'sound',
                    'badge'  => '+1',
                    'extras' => $extras
                ])
                ->androidNotification($msg, [
                    'title'  => $title,
                    'sound'  => 'sound',
                    'badge'  => '+1',
                    'inbox'  => 2,
                    'extras' => $extras
                ])->options([
                    'time_to_live' => 1
                ])->send();
        } else {
            $result = $push->setPlatform('all')
                ->options(['apns_production' => true])
                ->addAllAudience()
                ->iosNotification($msg, [
                    'title'  => $title,
                    'sound'  => 'sound',
                    'badge'  => '+1',
                    'extras' => $extras
                ])
                ->androidNotification($msg, [
                    'title'  => $title,
                    'sound'  => 'sound',
                    'badge'  => '+1',
                    'inbox'  => 2,
                    'extras' => $extras
                ])->options([
                    'time_to_live' => 1
                ])->send();
        }
    }

    /**
     * 判断用户是否还在读书会有没有被移除
     * @param $readPartyId 读书会的ID
     * @param $userId 用户的ID
     */
    public function is_belong_read_department($readPartyId, $userId)
    {
        $is_belong_read_department = DB::table('read_party_member')
            ->where(['read_party_id' => $readPartyId, 'user_id' => $userId, 'is_delete' => 0])
            ->get();
        $is_belong_read_department = count($is_belong_read_department) ? 1 : 0;//1表示还在这个读书会 0表示不在这个读书会了

        return $is_belong_read_department;
    }

    public function getCompanyIdByReadPartId($readPartId)
    {
        $companyId = DB::table('read_party')->where('ReaParID', $readPartId)->select('company_id')->first();
        $companyId = $companyId ? $companyId->company_id : 0;

        return $companyId;
    }


    /**
     * 获得多级评论
     * @param $contentId integer 要查找的内容的ID
     * @param $type integer 评论主体的类型
     * 1:为学习官的评论，
     * 2:为学习中心的文章的评论
     * 3:国政书吧或老侯代读视频
     * @param $commentId integer 单条评论ID 如果传递了该ID 则只会返回一条信息
     * @param $userId integer 获取本条评论的用户
     * @return array
     * */
    public function get_multy_grade_comments($contentId, $type, $commentId = 0, $userId = 0)
    {
        $sql = "SELECT
                      a.id,
                      a.pid,
                      a.user_id,
                      b.YourName,
                      b.FilePath1 as headImg,
                      a.replay_user_id,
                      IFNULL(d.YourName,'') replayYourName,
                      d.FilePath1 as replayHeadImg,
                      a.body,
                      IF(a.deleted_at,a.deleted_at,'') deleted_at,
                      a.created_at,
                      a.up_times,
                      FIND_IN_SET($userId,a.up_time_user) as is_like
                FROM comments a
                LEFT JOIN memberinfo b ON b.UserID = a.user_id
                LEFT JOIN memberinfo d ON d.UserID = a.replay_user_id
                WHERE a.lessons_id = $contentId
                AND   a.type      = $type
                ORDER BY a.id DESC ";

        $allComments = DB::select($sql);
        foreach ($allComments as $com) {
            $com->headImg       = change_member_head_img($com->headImg);
            $com->replayHeadImg = change_member_head_img($com->headImg);
            $com->is_like       = $com->is_like > 0 ? 1 : 0;
            $com->body          = emoji_text_decode($com->body);
        }

        $comments = [];
        foreach ($allComments as $key => $topComent) {
            if (($topComent->pid == 0 && $commentId == 0) || ($commentId == $topComent->id && $commentId > 0)) {
                $comment = $topComent;
                unset($allComments[$key]);
                if ($topComent->deleted_at) { //顶级评论删除的直接过滤
                    continue;
                }

                $comment->subComments = [];
                $parentIds            = [$comment->id];    //把某顶级下面的子评论ID都存储在此,以便寻找子评论的子评论
                foreach ($allComments as $childKey => $childComment) {
                    if (in_array($childComment->pid, $parentIds)) {
                        if (!$childComment->deleted_at) { //删除的只取ID，不去实际的数据
                            $childComment->subComments = [];
                            array_push($comment->subComments, $childComment);
                        }
                        array_push($parentIds, $childComment->id);
                        unset($allComments[$childKey]);
                    }
                }
                array_push($comments, $comment);
            }
        }

        return $comments;
    }


    /**
     * 获取单条评论以及下面的子评论
     * */
    public function get_comment($commentId)
    {
        $info     = DB::table('comments')->where('id', $commentId)->first();
        $comments = $this->get_multy_grade_comments($info->lessons_id, $info->type, $commentId);

        return $comments[0];
    }


}